package org.rapla.mobile.android.activity;

import org.rapla.facade.ClientFacade;
import org.rapla.mobile.android.service.FacadeService;
import org.rapla.mobile.android.service.FacadeService.FacadeServiceBinder;

import android.R.bool;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

/**
 * Base Activity
 * 
 * The base activity class provides methods and logic that is required across
 * multiple activities of this application. All activities are required to extend
 * this base class.
 * 
 * @author Maximilian Lenkeit <dev@lenki.com>
 */
public abstract class BaseActivity extends Activity {
	
	private ServiceConnection facadeServiceConnection;
	private FacadeService facadeService;
	private boolean facadeServiceBound;

	/**
	 * Get facade service 
	 * @return The currently running facade service instance
	 * @throws RuntimeException in case the facade service is not bound
	 */
	public FacadeService getFacadeService() throws RuntimeException {
		if(!facadeServiceBound) {
			throw new RuntimeException("Facade hasn't been initialized");
		}
		return this.facadeService;
	}
	
	/**
	 * Start facade service
	 * @param url Url of rapla server
	 * @param port Port of rapla server
	 * @param username Rapla system username
	 * @param password Password of user
	 */
	public void startFacadeService(String url, int port, String username, String password) {
		// Prepare intent
		Intent service = new Intent(this, FacadeService.class);
		service.putExtra("url", url);
		service.putExtra("port", port);
		service.putExtra("username", username);
		service.putExtra("password", password);
		
		// Defines callbacks for service binding, passed to bindService()
		facadeServiceConnection = new ServiceConnection() {

	        public void onServiceConnected(ComponentName className,
	                IBinder service) {
	            FacadeServiceBinder binder = (FacadeServiceBinder)service;
	            facadeService = binder.getService();
	            facadeServiceBound = true;
	        }

	        public void onServiceDisconnected(ComponentName arg0) {
	        	facadeServiceBound = false;
	        }
	    };
		
	    // Start service
		this.bindService(service, facadeServiceConnection, Context.BIND_AUTO_CREATE);
	}
	
	/**
	 * Stop facade service
	 */
	public void stopFacadeService() {
		if(this.facadeServiceBound) {
			// Stop service only if even started
			this.unbindService(facadeServiceConnection);
		}
	}
	
	/**
	 * Get facade
	 * @return Ready to use client facade instance
	 */
	public ClientFacade getFacade() {
		return this.getFacadeService().getFacade();
	}
}
